package com.anysoft.utils;

import android.content.Context;
import android.text.TextUtils;

import com.anysoft.config.AppConstant;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;


/**
 * Created by wwq on 2017/1/3.
 */

public class HttpUtil {
    
    public static String getMD5(String s) {
        try {
            // Create MD5 Hash
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();

            return toHexString(messageDigest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return "";
    }

    // String to byte
    public static String toHexString(byte[] b) {
        StringBuilder sb = new StringBuilder(b.length * 2);
        for (int i = 0; i < b.length; i++) {
            sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
            sb.append(HEX_DIGITS[b[i] & 0x0f]);
        }
        return sb.toString();
    }

    private static final char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F'};
    
    
    public static String getCommonParams2StringByWeb(Context context) {
        String param = "";
        String token = (TextUtils.isEmpty(AppConstant.token)) ? "" : AppConstant.token;
        param += "&token=" + token;
        return param;
    }
    
    /**
     * 将url转义转为map
     *
     * @param url
     * @return
     */
    public static HashMap<String, String> handleUrlParams(String url) {
        HashMap<String, String> hm = new HashMap<String, String>();
        try {
            url = URLDecoder.decode(url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (url.contains("?") && url.indexOf("?") != url.length() - 1) {
            String params = url.substring(url.indexOf("?") + 1);
            if (params.contains("&")) {
                String[] paramArr = params.split("&");
                for (int i = 0; i < paramArr.length; i++) {
                    String str = paramArr[i];
                    if (str.contains("=")) {
                        hm.put(str.substring(0, str.indexOf("=")),
                                str.substring(str.indexOf("=") + 1,
                                        str.length()));
                    }
                }
            } else {
                if (params.contains("=")) {
                    hm.put(params.substring(0, params.indexOf("=")),
                            params.substring(params.indexOf("=") + 1,
                                    params.length()));
                }
            }
        }
        return hm;
    }
}
